﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using StarsAdmin.Web.Core.Filter;
using Swashbuckle.AspNetCore.SwaggerUI;
using System.Reflection;

namespace StarsAdmin.Web.Core.Extensions
{
    public static class SwaggerExtension
    {
        public static void AddSwaggerConfig(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1.0",
                    Title = "系统管理",
                    Description = "系统管理模块",
                    Contact = new OpenApiContact
                    {
                        Name = "星辰",
                        Email = "1265914749@qq.com",
                        Url = new Uri("https://gitee.com/xuedejin/my_admin")
                    }
                });

                // 获得程序入口程序集
                var assembly = Assembly.GetEntryAssembly();
                if (assembly != null)
                {
                    string xmlFilename = $"{assembly?.GetName().Name}.xml";
                    //IncludeXmlComments 第二参数 true 则显示控制器注释
                    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
                }

                // 添加安全定义
                options.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header, // jwt默认存放Authorization信息的位置(请求头中)
                    Description = "请输入Login接口返回的Token，前置Bearer。示例：Bearer {Token}",
                    Name = "Authorization", // jwt默认的参数名称 -- 与标题头的参名相同
                    Type = SecuritySchemeType.ApiKey, //类型是 apikey
                    BearerFormat = "JWT",
                    Scheme = JwtBearerDefaults.AuthenticationScheme,
                });

                // 设置安全要求
                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference()
                            {
                                  Id = "Bearer",
                                  Type = ReferenceType.SecurityScheme
                            }
                        },
                        Array.Empty<string>()
                    }
                });
                // 设置默认参数过滤器
                options.OperationFilter<DefaultValueOperationFilter>();
                //添加接口文档排序过滤器
                options.DocumentFilter<OrderTagsDocumentFilter>();
                // 添加获取所有Api接口过滤器
                //options.DocumentFilter<ApiDocumentFilter>();
            });
        }

        public static void UseSwagger(this IApplicationBuilder app)
        {
            app.UseSwagger(options =>
            {
            });
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "系统管理 v1");

                // 打开时自动折叠
                options.DocExpansion(DocExpansion.None);

                //增加令牌本地缓存，刷新不会丢失
                options.ConfigObject.AdditionalItems.Add("persistAuthorization", "true");
                // 注入自定义token持久化JavaScript文件, 自动登录，
                options.InjectJavascript("/swagger_auto_login.js");
            });
        }
    }
}